// stripe-helper.js - Dedicated module for Stripe operations
const express = require('express');
const http = require('http');
const fs = require('fs');
const path = require('path');

// Create a dedicated log file for Stripe operations
const logFile = path.join(__dirname, 'stripe_operations.log');

// Helper function for logging Stripe operations
function logStripe(message, level = 'INFO') {
  const timestamp = new Date().toISOString();
  const logEntry = `[${timestamp}] [${level}] ${message}\n`;
  
  // Log to console
  console.log(logEntry);
  
  // Append to log file
  fs.appendFileSync(logFile, logEntry);
}

// Initialize the module
const initStripeHelper = (stripe) => {
  // Create dedicated Express app for Stripe operations
  const stripeApp = express();
  
  // Parse JSON request bodies
  stripeApp.use(express.json());
  
  // Initialize log file
  logStripe('Stripe helper service initializing...', 'INFO');
  
  // Middleware to log all requests to Stripe helper
  stripeApp.use((req, res, next) => {
    console.log(`Stripe helper received request: ${req.method} ${req.url}`);
    logStripe(`Received ${req.method} request to ${req.url}`, 'INFO');
    
    if (req.method === 'POST' || req.method === 'PUT') {
      logStripe(`Request body: ${JSON.stringify(req.body)}`, 'DEBUG');
    }
    
    next();
  });
  
  // CORS middleware for Stripe proxy
  stripeApp.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
    if (req.method === 'OPTIONS') {
      return res.status(200).end();
    }
    
    next();
  });
  
  // Stripe Proxy API - Handle all Stripe operations here
  stripeApp.post('/:action', async (req, res) => {
    const action = req.params.action;
    const data = req.body;
    
    logStripe(`Processing Stripe action: ${action}`, 'INFO');
    logStripe(`Request data: ${JSON.stringify(data)}`, 'DEBUG');
    
    try {
      let result;
      
      switch(action) {
        case 'create-payment-method':
          // Not typically needed as this is handled by Stripe.js
          // Included for completeness
          logStripe('Creating payment method', 'INFO');
          result = await stripe.paymentMethods.create({
            type: 'card',
            card: data.card,
            billing_details: data.billing_details
          });
          break;
          
        case 'create-customer':
          logStripe(`Creating customer for email: ${data.email}`, 'INFO');
          result = await stripe.customers.create({
            email: data.email,
            name: data.name || '',
            metadata: {
              companyName: data.companyName || '',
              created_from: 'subscription_form'
            }
          });
          break;
          
        case 'attach-payment-method':
          logStripe(`Attaching payment method ${data.paymentMethodId} to customer ${data.customerId}`, 'INFO');
          result = await stripe.paymentMethods.attach(
            data.paymentMethodId,
            { customer: data.customerId }
          );
          break;
          
        case 'set-default-payment-method':
          logStripe(`Setting default payment method for customer ${data.customerId}`, 'INFO');
          result = await stripe.customers.update(
            data.customerId,
            {
              invoice_settings: {
                default_payment_method: data.paymentMethodId
              }
            }
          );
          break;
          
        case 'create-subscription':
          logStripe(`Creating subscription for customer ${data.customerId} to plan ${data.planId}`, 'INFO');
          result = await stripe.subscriptions.create({
            customer: data.customerId,
            items: [{ price: data.planId }],
            expand: ['latest_invoice.payment_intent']
          });
          break;
          
        case 'create-direct-subscription':
          // Combined operation that does everything in one request
          logStripe(`Processing complete subscription for ${data.email} to plan ${data.planId}`, 'INFO');
          
          // Step 1: Create customer
          const customer = await stripe.customers.create({
            email: data.email,
            name: data.name || '',
            metadata: {
              companyName: data.companyName || '',
              created_from: 'subscription_form'
            }
          });
          logStripe(`Created customer: ${customer.id}`, 'INFO');
          
          // Step 2: Attach payment method
          await stripe.paymentMethods.attach(
            data.paymentMethodId,
            { customer: customer.id }
          );
          logStripe(`Attached payment method ${data.paymentMethodId}`, 'INFO');
          
          // Step 3: Set as default payment method
          await stripe.customers.update(
            customer.id,
            {
              invoice_settings: {
                default_payment_method: data.paymentMethodId
              }
            }
          );
          logStripe(`Set default payment method`, 'INFO');
          
          // Step 4: Create subscription
          const subscription = await stripe.subscriptions.create({
            customer: customer.id,
            items: [{ price: data.planId }],
            expand: ['latest_invoice.payment_intent']
          });
          logStripe(`Created subscription: ${subscription.id}`, 'INFO');
          
          // Generate a simple token
          const tokenData = {
            email: data.email,
            name: data.name || '',
            companyName: data.companyName || '',
            accountId: customer.id
          };
          const token = Buffer.from(JSON.stringify(tokenData)).toString('base64')
            .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
          
          result = {
            success: true,
            customerId: customer.id,
            subscriptionId: subscription.id,
            token: token,
            loginLink: `https://${req.headers.host}?token=${token}`
          };
          break;
          
        case 'cancel-subscription':
          logStripe(`Canceling subscription ${data.subscriptionId}`, 'INFO');
          result = await stripe.subscriptions.update(
            data.subscriptionId,
            { cancel_at_period_end: true }
          );
          break;
          
        case 'get-subscription':
          logStripe(`Getting subscription details for ${data.customerId}`, 'INFO');
          const subscriptions = await stripe.subscriptions.list({
            customer: data.customerId,
            status: 'active',
            limit: 1
          });
          
          if (subscriptions.data.length === 0) {
            result = { hasSubscription: false };
          } else {
            const sub = subscriptions.data[0];
            result = {
              hasSubscription: true,
              subscriptionId: sub.id,
              status: sub.status,
              currentPeriodStart: sub.current_period_start,
              currentPeriodEnd: sub.current_period_end,
              planId: sub.items.data[0].price.id
            };
          }
          break;
          
        default:
          logStripe(`Unknown action: ${action}`, 'ERROR');
          return res.status(400).json({ error: `Unknown action: ${action}` });
      }
      
      logStripe(`Stripe operation successful: ${action}`, 'SUCCESS');
      res.json(result);
    } catch (error) {
      logStripe(`Stripe error: ${error.message}`, 'ERROR');
      logStripe(`Error details: ${JSON.stringify(error)}`, 'ERROR');
      res.status(400).json({ error: error.message });
    }
  });
  
  // Create a separate HTTP server for Stripe operations on port 6000
  const stripeServer = http.createServer(stripeApp);
  stripeServer.listen(6000, 'localhost', () => {
    console.log('Stripe helper HTTP server running on http://localhost:6000');
    logStripe('Stripe helper server started on port 6000', 'SUCCESS');
  });
  
  return {
    app: stripeApp,
    server: stripeServer
  };
};

module.exports = { initStripeHelper };

